<?php
	
function get_user_id($username){
	$q = new DBQuery;
	$q->addTable('users','u');
	$q->addQuery('user_id');
	$q->addWhere("user_username='$username'");
	$users = $q->loadList();

	if(isset($users) && isset($users[0]['user_id'])) return $users[0]['user_id'];
	else return false;
}

function create_user($email,$first_name,$last_name){
	global $AppUI;

	$obj = new CUser();
	$contact = new CContact();
	$random=md5(rand());
	$user=array('user_username'=>"$email",'user_id'=>0,'user_type'=>0,'user_parent'=>null,
			'user_signature'=>'','user_password'=>"$random",'user_role'=>14);
	$cont=array('contact_first_name'=>"$first_name",'contact_last_name'=>"$last_name",'contact_company'=>'',
			'contact_email'=>"$email",'contact_department'=>'','contact_id'=>0);

	if (!$obj->bind($user)) {
		throw new Exception( "user details binding failed");
	}
	if (!$contact->bind($cont)) {
		throw new Exception( "contact details binding failed");
	}
	
	$obj_user->first_name=$first_name;
	$obj_user->last_name=$last_name;
	$obj->user_username = mb_strtolower($obj->user_username);

	// prepare (and translate) the module name ready for the suffix
	$AppUI->setMsg('User');

	// !User's contact information not deleted - left for history.
	// check if a user with the param Username already exists
	$userEx = FALSE;

	$contact->contact_owner = $AppUI->user_id;


	if (($msg = $contact->store())) {
		throw new Exception( "contact faild: $msg");
	} else {        
		$obj->user_contact = $contact->contact_id;
		if (($msg = $obj->store())) {
			throw new Exception( "contact faild: $msg");
		}
		if (true) {
			$perms =& $AppUI->acl();
			if ($perms->insertUserRole(14, $obj->user_id)) {
				$AppUI->setMsg('', UI_MSG_ALERT, true);
			} else {
				$AppUI->setMsg('failed to add role', UI_MSG_ERROR);
			}
		}
	}
}

